Protected vs Public in terms of Inheritance in Java
Protected vs Public in terms of Inheritance in Java
16718-Aug-2023
Updated on 19-Aug-2023
Home / DeveloperSection / Forums / Protected vs Public in terms of Inheritance in Java
Protected vs Public in terms of Inheritance in Java
Aryan Kumar
19-Aug-2023In Java, the access modifiers
public
andprotected
are used to control the visibility of members of a class, such as variables, methods, and constructors.In terms of inheritance, the main difference between
public
andprotected
is thatprotected
members are only accessible to subclasses, even if the subclass is in a different package. This means thatprotected
members can be used to implement an inheritance hierarchy without exposing the implementation details to other classes.For example, let's say we have a class called
Animal
with aprotected
method calledgetSound()
. This method returns the sound that the animal makes. We can then create a subclass ofAnimal
calledDog
. TheDog
class can override thegetSound()
method to return the sound that a dog makes. However, other classes outside of theAnimal
andDog
packages cannot access thegetSound()
method.Here is a table summarizing the visibility of
public
andprotected
members in Java:When choosing between
public
andprotected
, you should consider the following factors:public
.protected
.private
.